"""
课堂质量评估相关的数据模型
避免Pydantic版本兼容性问题，使用简单的数据类
"""
from datetime import datetime
from typing import List, Dict, Optional, Any, Tuple
from dataclasses import dataclass
from enum import Enum


class AttentionLevel(str, Enum):
    """专注度等级枚举"""
    VERY_HIGH = "very_high"
    HIGH = "high"
    MEDIUM = "medium"
    LOW = "low"
    VERY_LOW = "very_low"


class ParticipationLevel(str, Enum):
    """参与度等级枚举"""
    VERY_ACTIVE = "very_active"
    ACTIVE = "active"
    MODERATE = "moderate"
    PASSIVE = "passive"
    INACTIVE = "inactive"


class LearningBehavior(str, Enum):
    """学习行为类型枚举"""
    LISTENING = "listening"
    TAKING_NOTES = "taking_notes"
    RAISING_HAND = "raising_hand"
    DISCUSSING = "discussing"
    READING = "reading"
    DISTRACTED = "distracted"
    SLEEPING = "sleeping"
    USING_PHONE = "using_phone"


class ClassroomAtmosphere(str, Enum):
    """课堂氛围枚举"""
    EXCELLENT = "excellent"
    GOOD = "good"
    AVERAGE = "average"
    POOR = "poor"
    VERY_POOR = "very_poor"


@dataclass
class AttentionAnalysisRequest:
    """专注度分析请求"""
    classroom_id: str
    session_id: str
    image_data: str  # base64编码的图像数据
    student_detections: List[Dict[str, Any]]
    timestamp: datetime


@dataclass
class AttentionAnalysisResponse:
    """专注度分析响应"""
    analysis_id: str
    classroom_id: str
    session_id: str
    timestamp: datetime
    student_attention_data: List[Dict[str, Any]]
    average_attention_score: float
    attention_distribution: Dict[str, int]


@dataclass
class ParticipationAnalysisRequest:
    """参与度分析请求"""
    classroom_id: str
    session_id: str
    student_ids: List[str]
    audio_features: Optional[Dict[str, Any]] = None
    timestamp: Optional[datetime] = None


@dataclass
class ParticipationAnalysisResponse:
    """参与度分析响应"""
    analysis_id: str
    classroom_id: str
    session_id: str
    timestamp: datetime
    student_participation_data: List[Dict[str, Any]]
    average_participation_score: float
    participation_distribution: Dict[str, int]


@dataclass
class ClassroomSessionAnalysisRequest:
    """课堂会话分析请求"""
    classroom_id: str
    session_id: str
    start_time: Optional[datetime] = None
    end_time: Optional[datetime] = None


@dataclass
class ClassroomSessionAnalysisResponse:
    """课堂会话分析响应"""
    analysis_id: str
    classroom_id: str
    session_id: str
    analysis_period: Tuple[datetime, datetime]
    student_count: int
    average_attention_score: float
    average_participation_score: float
    attention_distribution: Dict[str, int]
    participation_distribution: Dict[str, int]
    behavior_statistics: Dict[str, int]
    classroom_atmosphere: str
    engagement_trends: Dict[str, Any]
    learning_effectiveness: float
    recommendations: List[str]


@dataclass
class LearningPredictionRequest:
    """学习效果预测请求"""
    student_id: str
    prediction_period: Optional[int] = 30  # 预测天数


@dataclass
class LearningPredictionResponse:
    """学习效果预测响应"""
    student_id: str
    prediction_id: str
    predicted_performance: float
    risk_level: str
    learning_style: str
    strengths: List[str]
    weaknesses: List[str]
    recommendations: List[str]
    confidence: float
    generated_at: datetime


@dataclass
class StudentAttentionSummaryRequest:
    """学生专注度摘要请求"""
    student_id: str
    start_time: Optional[datetime] = None
    end_time: Optional[datetime] = None


@dataclass
class StudentAttentionSummaryResponse:
    """学生专注度摘要响应"""
    student_id: str
    data_count: int
    time_range: Optional[Tuple[datetime, datetime]]
    average_attention_score: float
    max_attention_score: float
    min_attention_score: float
    attention_stability: float
    attention_level_distribution: Dict[str, int]
    behavior_distribution: Dict[str, int]
    most_common_level: str
    most_common_behavior: str


@dataclass
class ClassroomStatisticsRequest:
    """课堂统计请求"""
    classroom_id: str
    start_time: Optional[datetime] = None
    end_time: Optional[datetime] = None


@dataclass
class ClassroomStatisticsResponse:
    """课堂统计响应"""
    classroom_id: str
    analysis_count: int
    time_range: Optional[Tuple[datetime, datetime]]
    average_attention_score: float
    average_participation_score: float
    average_learning_effectiveness: float
    attention_score_trend: str
    participation_score_trend: str
    atmosphere_distribution: Dict[str, int]
    most_common_atmosphere: str
    total_students_analyzed: int


@dataclass
class StudentBehaviorAnalysisRequest:
    """学生行为分析请求"""
    student_id: str
    behavior_type: Optional[str] = None
    start_time: Optional[datetime] = None
    end_time: Optional[datetime] = None


@dataclass
class StudentBehaviorAnalysisResponse:
    """学生行为分析响应"""
    student_id: str
    analysis_period: Tuple[datetime, datetime]
    behavior_statistics: Dict[str, Any]
    behavior_patterns: Dict[str, Any]
    attention_correlation: Dict[str, float]
    recommendations: List[str]


@dataclass
class ClassroomComparisonRequest:
    """课堂对比请求"""
    classroom_ids: List[str]
    comparison_metrics: List[str]  # attention, participation, atmosphere, effectiveness
    start_time: Optional[datetime] = None
    end_time: Optional[datetime] = None


@dataclass
class ClassroomComparisonResponse:
    """课堂对比响应"""
    comparison_id: str
    classroom_ids: List[str]
    comparison_period: Tuple[datetime, datetime]
    comparison_metrics: List[str]
    comparison_data: Dict[str, Dict[str, Any]]
    rankings: Dict[str, List[Dict[str, Any]]]
    insights: List[str]


@dataclass
class AttentionTrendRequest:
    """专注度趋势请求"""
    target_type: str  # student, classroom, global
    target_id: Optional[str] = None
    start_time: Optional[datetime] = None
    end_time: Optional[datetime] = None
    granularity: str = "hour"  # hour, day, week


@dataclass
class AttentionTrendResponse:
    """专注度趋势响应"""
    target_type: str
    target_id: Optional[str]
    analysis_period: Tuple[datetime, datetime]
    granularity: str
    trend_data: List[Dict[str, Any]]
    trend_analysis: Dict[str, Any]
    forecasting: Optional[Dict[str, Any]]


@dataclass
class LearningEffectivenessRequest:
    """学习有效性评估请求"""
    classroom_id: str
    session_id: Optional[str] = None
    evaluation_criteria: List[str] = None


@dataclass
class LearningEffectivenessResponse:
    """学习有效性评估响应"""
    classroom_id: str
    session_id: Optional[str]
    evaluation_period: Tuple[datetime, datetime]
    effectiveness_score: float
    effectiveness_grade: str
    contributing_factors: Dict[str, float]
    improvement_suggestions: List[str]
    benchmark_comparison: Dict[str, Any]


@dataclass
class StudentEngagementRequest:
    """学生参与度评估请求"""
    student_id: str
    engagement_metrics: List[str] = None
    start_time: Optional[datetime] = None
    end_time: Optional[datetime] = None


@dataclass
class StudentEngagementResponse:
    """学生参与度评估响应"""
    student_id: str
    evaluation_period: Tuple[datetime, datetime]
    engagement_score: float
    engagement_level: str
    engagement_metrics: Dict[str, float]
    engagement_patterns: Dict[str, Any]
    improvement_recommendations: List[str]


@dataclass
class ClassroomAlertRequest:
    """课堂告警请求"""
    classroom_id: str
    alert_types: List[str]  # low_attention, poor_participation, negative_atmosphere
    threshold_settings: Dict[str, float]


@dataclass
class ClassroomAlertResponse:
    """课堂告警响应"""
    alert_id: str
    classroom_id: str
    alert_type: str
    alert_level: str  # low, medium, high, critical
    alert_message: str
    current_values: Dict[str, float]
    threshold_values: Dict[str, float]
    recommendations: List[str]
    triggered_at: datetime


@dataclass
class TeachingQualityRequest:
    """教学质量评估请求"""
    classroom_id: str
    teacher_id: Optional[str] = None
    evaluation_period: Tuple[datetime, datetime]
    quality_dimensions: List[str] = None


@dataclass
class TeachingQualityResponse:
    """教学质量评估响应"""
    evaluation_id: str
    classroom_id: str
    teacher_id: Optional[str]
    evaluation_period: Tuple[datetime, datetime]
    overall_quality_score: float
    quality_dimensions: Dict[str, float]
    student_feedback_summary: Dict[str, Any]
    improvement_areas: List[str]
    best_practices: List[str]


# 辅助函数
def to_dict(obj) -> Dict[str, Any]:
    """将数据类转换为字典"""
    if hasattr(obj, '__dict__'):
        result = {}
        for key, value in obj.__dict__.items():
            if isinstance(value, datetime):
                result[key] = value.isoformat()
            elif isinstance(value, Enum):
                result[key] = value.value
            elif isinstance(value, (list, tuple)):
                result[key] = [to_dict(item) if hasattr(item, '__dict__') else item for item in value]
            elif isinstance(value, dict):
                result[key] = {k: to_dict(v) if hasattr(v, '__dict__') else v for k, v in value.items()}
            else:
                result[key] = value
        return result
    return obj


def from_dict(data_class, data: Dict[str, Any]):
    """从字典创建数据类实例"""
    if not hasattr(data_class, '__annotations__'):
        return data
    
    kwargs = {}
    for field_name, field_type in data_class.__annotations__.items():
        if field_name in data:
            value = data[field_name]
            
            # 处理datetime类型
            if field_type == datetime and isinstance(value, str):
                kwargs[field_name] = datetime.fromisoformat(value)
            # 处理Optional类型
            elif hasattr(field_type, '__origin__') and field_type.__origin__ is Union:
                kwargs[field_name] = value
            else:
                kwargs[field_name] = value
    
    return data_class(**kwargs)